<?php
/**
 * Admin.php
 * Author: luoji (867404364@qq.com)
 * Date: 2020-12-18
 * Time: 15:31
 */

namespace App\Http\Controllers\Tool;


use App\Http\Controllers\Base;
use App\Tables;
use App\Tool\RandomStr;

class Admin extends Base
{
    const KEY = "whsjxggcbyxgs123456";

    public function showAdd()
    {
        if(!$this->checkKey()){
            abort(404);
            return false;
        }

        $adminList = Tables\Admin::select('username')->get();
        return view('tool/addAdmin', ['adminList' => $adminList]);
    }

    public function add()
    {
        $oUrl = $this->request->server->get('HTTP_REFERER', '');
        $key = [];
        parse_str(parse_url($oUrl)['query'], $key);
        if(!$this->checkKey($key['key']??'')) {
            abort(404);
        }
        $username = $this->request->post('username', '');
        $password = $this->request->post('password', '');
        $repass  = $this->request->post('repass', '');

        if(empty($username) or empty($password) or empty($repass)) {
            return $this->responseFail('有空值!');
        }

        if($password !== $repass) {
            return $this->responseFail('两次密码不一样!');
        }

        $find = Tables\Admin::where(['username' => $username])->first();
        if(!empty($find)) {
            return $this->responseFail('用户重复');
        }
        $salt = RandomStr::make();
        $password = md5(md5($password).md5($salt));
        $id = Tables\Admin::insertGetId([
            'username' => $username,
            'password' => $password,
            'salt'     => $salt,
            'add_time' => time()
        ]);
        if($id > 0 ) {
            return $this->responseSuccess();
        } else {
            return $this->responseFail('错误了！');
        }
    }

    private  function  checkKey($key='')
    {
        if(empty($key)) {
            $key = $this->request->get('key', null);
        }
        if($key === null || $key !== self::KEY) {
            return false;
        } else {
            return true;
        }
    }


}